package org.com.lcuiot.handler;

import org.com.lcuiot.database.dto.Result;
import org.com.lcuiot.database.entity.DeviceData;
import org.com.lcuiot.security.GetTokenInfo;
import org.com.lcuiot.security.JwtUser;
import org.com.lcuiot.service.DeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.concurrent.atomic.AtomicReference;

import static org.springframework.web.reactive.function.server.RouterFunctions.route;


/**
 * 设备数据点处理器
 *
 * @author gaoge
 * @since 2022/10/31 11:32
 */
@RestController
public class DeviceDataHandler extends AbstractHandler {
    private final DeviceDataService deviceDataService;

    @Autowired
    public DeviceDataHandler(DeviceDataService deviceDataService) {
        this.deviceDataService = deviceDataService;
    }


    @Bean
    public RouterFunction<ServerResponse> deviceDataRouter() {
        return route()
                .GET("/query_sensor_data/{areaId}", this::queryAllDataStreamInfo)
                .build();
    }

    /**
     * 添加设备数据点信息
     *
     * @param request 请求参数
     * @return Mono<ServerResponse>
     * @author gaoge
     */
    public Mono<ServerResponse> addDeviceDataHandler(ServerRequest request) {
        return request.bodyToMono(DeviceData.class)
                .flatMap(s -> {
                    Result<Object> result = deviceDataService.addDeviceData(s);
                    return resolveResult(result);
                });
    }

    /**
     * 根据机构ID查询所有数据流数据信息
     *
     * @param request 请求信息
     * @return Mono<ServerResponse>
     * @author gaoge
     */
    public Mono<ServerResponse> queryAllDataStreamInfo(ServerRequest request) {
        Long areaId = Long.valueOf(request.pathVariable("areaId"));
        return GetTokenInfo.getAuthentication().flatMap(auth ->
        {
            Result<Object> result = deviceDataService.queryAllDataStreamInfo(areaId, auth.getOrganizationId());
            return ServerResponse.status(result.getCode()).body(Mono.just(result), Result.class);
        });
    }
}
